const axios = require('axios')
const fs = require('fs')
const crypto = require('crypto')
const Store = require('electron-store')

const store = new Store()
const clientId = '1788123142414403'
const clientSecret = '40aed01eb3855ab362faeb914a0dc693d88b64b9'
async function postRefreshToken(refresh_token) {
  const url = 'https://api.oceanengine.com/open_api/oauth2/refresh_token/'
  try {
    const response = await axios.post(
      url,
      {
        app_id: clientId,
        secret: clientSecret,
        refresh_token // 如果是授权码模式需要此参数
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    return response.data?.data
  } catch (error) {
    console.error('刷新 Token 失败:', error.response?.data || error.message)
    throw error
  }
}

async function getAccessToken(auth_code) {
  const url = 'https://ad.oceanengine.com/open_api/oauth2/access_token/'
  try {
    const response = await axios.post(
      url,
      {
        app_id: clientId,
        secret: clientSecret,
        grant_type: 'auth_code', // 根据实际情况调整 grant_type
        auth_code // 如果是授权码模式需要此参数
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    console.log('Access Token:', response.data?.data)
    return response.data?.data
  } catch (error) {
    console.error('获取 Token 失败:', error.response?.data || error.message)
    throw error
  }
}
function calculateMD5(filePath) {
  const hash = crypto.createHash('md5')
  const stream = fs.createReadStream(filePath)
  return new Promise((resolve, reject) => {
    stream.on('data', (chunk) => hash.update(chunk))
    stream.on('error', reject)
    stream.on('end', () => resolve(hash.digest('hex')))
  })
}
async function uploadVideo(options = {}) {
  const token = store.get('access_token')
  const { advertiser_id, video_file, filename } = options || {}
  const form = new FormData()
  const url = 'https://api.oceanengine.com/open_api/2/file/video/ad/'

  try {
    form.append('advertiser_id', advertiser_id)
    const fileBuffer = fs.readFileSync(video_file)
    const blob = new Blob([fileBuffer], { type: 'video/mp4' })
    const videoSignature = await calculateMD5(video_file)
    form.append('video_file', blob, filename)
    form.append('filename', filename)
    form.append('video_signature', videoSignature)
    const response = await axios.post(url, form, {
      headers: {
        'Access-Token': token,
        'Content-Type': 'multipart/form-data' // 设置请求头为multipart/form-data
      }
    })

    return {
      ...response.data,
      filename
    }
  } catch (error) {
    console.error('上传失败:', error)
    throw error
  }
}
async function getCustomConfig() {
  const url = 'https://api.oceanengine.com/open_api/v3.0/report/custom/config/get/'
  const token = store.get('access_token')
  try {
    const response = await axios({
      method: 'get',
      url: `${url}?advertiser_id=1825534179999769&data_topics=${encodeURIComponent(JSON.stringify(['BASIC_DATA']))}`,
      headers: {
        'Content-Type': 'application/json',
        'Access-Token': token // 将 Access-Token 添加到请求头中
      }
    })
    // console.log("config:", JSON.stringify(response.data, null, 2));
    return response.data?.data
  } catch (error) {
    throw error
  }
}
function objectToUrlParams(obj) {
  const params = []
  for (const [key, value] of Object.entries(obj)) {
    if (Array.isArray(value)) {
      const stringifiesValue = JSON.stringify(value)
      params.push(`${key}=${encodeURIComponent(stringifiesValue)}`)
    } else {
      params.push(`${key}=${encodeURIComponent(value)}`)
    }
  }
  return params.join('&')
}

async function getCustomReport(data) {
  const url = 'https://api.oceanengine.com/open_api/v3.0/report/custom/get/'
  const token = store.get('access_token')
  try {
    const response = await axios.get(`${url}?${objectToUrlParams(data)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Access-Token': token // 将 Access-Token 添加到请求头中
      }
    })
    // console.log("config:", JSON.stringify(response.data, null, 2));
    return response.data?.data
  } catch (error) {
    throw error
  }
}
async function postWeekScheduleUpdate(data) {
  const url = 'https://api.oceanengine.com/open_api/v3.0/project/week_schedule/update/'
  const token = store.get('access_token')
  try {
    const response = await axios.post(`${url}`, data, {
      headers: {
        'Content-Type': 'application/json',
        'Access-Token': token // 将 Access-Token 添加到请求头中
      }
    })
    // console.log('update')
    // console.log("config:", JSON.stringify(response.data, null, 2));
    // console.log(response.data)
    return response.data?.data
  } catch (error) {
    throw error
  }
}

module.exports = {
  getAccessToken,
  uploadVideo,
  postRefreshToken,
  getCustomConfig,
  getCustomReport,
  postWeekScheduleUpdate
}
